package service

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// 获取优惠券列表
func GetCoupon(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取用户信息
	var userData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&userData).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var list []models.MCoupon
	var count int64
	err = models.DB.Model(new(models.MCoupon)).Where("status=? AND stock>?", 1, 0).Count(&count).Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	var recordData []models.MCouponRecord
	err = models.DB.Model(new(models.MCouponRecord)).Where("mid=?", jsonData.Mid).Find(&recordData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	var listCoupon []models.MCoupon
	for _, v := range list {
		if v.Yxqtype == 2 {
			v.Yxqdate = v.Yxqdate*86400 + int(time.Now().Unix())
		}
		//判断该用户是否显示
		cur := false
		//是否是在领取的时间
		if v.Endtime > 0 {
			if time.Now().Unix() > int64(v.Starttime) && time.Now().Unix() < int64(v.Endtime) {
				cur = true
			} else {
				continue
			}
		}
		//判断用户是否满足领取等级
		curShowtj := false
		for _, m := range strings.Split(v.Showtj, ",") {
			n, _ := strconv.Atoi(m)
			if n == -1 || n == userData.Levelid {
				curShowtj = true
				break
			} else {
				curShowtj = false
			}
		}
		if curShowtj == true {
			cur = true
		} else {
			continue
		}
		//判断用户是否已领取或者领取达到上线
		num := 0
		for _, j := range recordData {
			if j.Couponid == v.ID {
				num++
			}
		}
		if num == 0 || num < v.Perlimit {
			cur = true
		} else {
			continue
		}
		if cur == true {
			listCoupon = append(listCoupon, v)
		}
	}
	//成功
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     define.Success,
		"data": map[string]interface{}{
			"list":  listCoupon,
			"count": count,
		},
	})
}

// 领取优惠券
func ReceiveCoupon(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []models.MCouponRecord
	var count int64
	err = models.DB.Model(new(models.MCouponRecord)).Where("mid=? AND couponid=?", jsonData.Mid, jsonData.Id).Count(&count).Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//获取优惠券信息
	var couponData models.MCoupon
	err = models.DB.Model(new(models.MCoupon)).Where("id=? AND aid=?", jsonData.Id, jsonData.Aid).First(&couponData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}

	if int(count) >= couponData.Perlimit { //判断用户是否已达到领取的限额
		define.Response.ResultFail(c, 10004, "你已领取了这张优惠券!", "")
		return
	}
	//是否是在领取的时间
	if couponData.Endtime > 0 {
		if time.Now().Unix() < int64(couponData.Starttime) { //判断是否开始领券
			define.Response.ResultFail(c, 10006, "领取优惠券的期限尚未开始", "")
			return
		}
		if time.Now().Unix() > int64(couponData.Endtime) { //判断是否已过领券时间
			define.Response.ResultFail(c, 10007, "获取优惠券的期限已过期", "")
			return
		}
	}
	//获取用户信息
	var userData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&userData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	//判断用户是否满足领取等级
	curGettj := false
	for _, m := range strings.Split(couponData.Gettj, ",") {
		n, _ := strconv.Atoi(m)
		if n == -1 || n == userData.Levelid {
			curGettj = true
			break
		} else {
			curGettj = false
		}
	}
	if curGettj != true {
		define.Response.ResultFail(c, 10005, "您的等级不足以获得优惠券!", "")
		return
	}

	//生成随机码
	var RandomStr string
	RandomStr = string(define.Krand(16, define.KC_RAND_KIND_ALL))
	couponData1 := map[string]interface{}{
		"aid":        jsonData.Aid,
		"mid":        jsonData.Mid,
		"couponid":   jsonData.Id,
		"couponname": couponData.Name,
		"money":      couponData.Money,
		"minprice":   couponData.Minprice,
		"starttime":  couponData.Starttime,
		"endtime":    couponData.Endtime,
		"createtime": int(time.Now().Unix()),
		"status":     0,
		"type":       couponData.Type,
		"used_count": 0,
		"code":       RandomStr,
		"hexiaoqr":   "hhhhhh",
		"remark":     couponData.Usetips,
	}
	if couponData.Yxqtype == 2 {
		couponData1["usetime"] = int(int64(couponData.Yxqdate*86400) + time.Now().Unix())
	} else {
		couponData1["usetime"] = couponData.YxqendTime
	}
	err = models.DB.Model(new(models.MCouponRecord)).Create(&couponData1).Error
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//成功
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     define.Success,
		"data":    "",
	})
}

type MyCouponList struct {
	ID         int             `json:"id"`
	Couponid   int             `json:"couponid"`   //优惠券ID
	Couponname string          `json:"couponname"` //优惠券名称
	Money      decimal.Decimal `json:"money"`      //优惠金额
	Minprice   decimal.Decimal `json:"minprice"`   //最低消费金额
	Status     int             `json:"status"`     //状态0未使用1已使用2过期
	Usetime    int             `json:"usetime"`    //使用时间
	Type       int             `json:"type"`       //1代金券
	Fwtype     int             `json:"fwtype"`     //0全场通用,1指定类目,2指定服务商品,
	Remark     string          `json:"remark"`     //
}

// 获取我的优惠券
func GetMyCouponList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var list []MyCouponList
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData := "m_coupon_record.id,m_coupon_record.couponid,m_coupon_record.couponname,m_coupon_record.money,m_coupon_record.remark,m_coupon_record.minprice" +
		",m_coupon_record.status,m_coupon_record.usetime,m_coupon.type,m_coupon.fwtype"
	err = models.DB.Table("m_coupon_record").Select(selectData).Joins("left join m_coupon on m_coupon.id=m_coupon_record.couponid").Where("m_coupon_record.mid=? AND m_coupon_record.status=?", jsonData.Mid, jsonData.Status).Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Find(&list).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//成功
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     define.Success,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}
